#include "precompile.h"

#include "MainFrame.h"
#include "Application.h"
#include "workspace/IController.h"
#include "form/IControlBars.h"
#include "form/IPanes.h"
#include "form/IForm.h"

MainFrame::MainFrame()
{
}

MainFrame::~MainFrame()
{
}

IControlBars* MainFrame::GetControlBars() const
{
	if (m_objControlBars.IsNull())
		m_objControlBars.CreateObject(CLSID_ControlBars);
	sys::InterfacePtr<IControlBars> pIFControlBars(m_objControlBars);
	return pIFControlBars;
}

IMenuBar* MainFrame::GetMenuBar() const
{
	return GetControlBars()->GetMenuBar();
}

IToolBar* MainFrame::GetToolbox() const
{
	return GetControlBars()->GetToolbox();
}

IPanes* MainFrame::GetPanes() const
{
	if (m_objPanes.IsNull())
		m_objPanes.CreateObject(CLSID_Panes);
	sys::InterfacePtr<IPanes> pIFPanes(m_objPanes);
	return pIFPanes;
}

IForm* MainFrame::CreateForm(uint32 category)
{
	IObject* pFormObj = NULL;
	FormDictionary::const_iterator itfind = m_forms.find(category);
	if (itfind == m_forms.end())
	{
		sys::ObjectPtr objForm;
		objForm.CreateObject(CLSID_Form);
		if (objForm.IsNotNull())
		{
			m_forms[category] = objForm;
		}
		pFormObj = objForm.P();
	}
	else
		pFormObj = itfind->second.P();

	if (!pFormObj)
		return NULL;

	sys::InterfacePtr<IForm> pIFForm(pFormObj);
	pIFForm->Setwindow(NULL);

	//FormCreateEventArgs args(pFormObj,category);
	//if (FormCreating() && FormCreating()(_getself<IMainFrame>(this),&args))
	//	return pIFForm;

	return NULL;

}

bool MainFrame::RouteCommandMessenge(SystemEventArgs* e)
{
	sys::ObjectPtr objApplication;
	objApplication.CreateObject(CLSID_Application);
	sys::InterfacePtr<IApplication> pIFApplication(objApplication);

	IObject* control = GetControlBars()->FindControl(e->GetCommandID());

	if (!e->IsCommandStateEnabled())
	{
		if (getSystemEvent()->ExecuteCommand() (sys::getSelf<IMainFrame>(this),e) )
			return true;

		if (control)
		{
			sys::InterfacePtr<IControl> pIFControl(control);
			if (pIFControl->Click()(control,e))
				return true;
		}

		//if (pIFApplication->GetController()->ExecuteCommand(e))
		//	return true;
	}
	else if(e->IsCommandStateEnabled())
	{
		if (getSystemEvent()->UpdateUI() (sys::getSelf<IMainFrame>(this),e) )
			return true;

		if (control)
		{
			sys::InterfacePtr<IControl> pIFControl(control);
			if (pIFControl->UpdateUI()(control,e))
				return true;
		}

		//if (pIFApplication->GetController()->UpdateUI(e))
		//	return true;
	}

	return false;
}